<template>
  <scroll class="suggest"
          :data="ret"
          :pullup="pullup"
          @scrollToEnd="searchMove"
          ref="suggest"
          :beforeScroll="beforeScroll"
          @beforeScroll="listScroll"
    >

    <ul class="suggest-list" >
      <li @click="selectItem(item)" class="suggest-item" v-for="item in ret">
        <div class="icon">
          <i :class="getIconCls(item)"></i>
        </div>
        <div class="name">
          <p class="text" v-html="getDisplayName(item)"></p>
        </div>
      </li>
      <loading v-show="hasMore" title=""></loading>
    </ul>
    <div class="no-result-wrapper" v-show="!hasMore && this.query !== this.search.keyword">
      <no-result title="抱歉，暂无搜索结果"></no-result>
    </div>
  </scroll>
</template>

<script type="text/ecmascript-6">
  import {search} from "../../api/search";
  import {ERR_OK} from "../../api/config";
  import {createSong, isValidMusic} from "../../common/js/song";
  import scroll from '../../base/scroll/scroll'
  import Loading from "../../base/loading/loading";
  import Singer from '../../common/js/singer'
  import {mapMutations,mapActions,mapGetters} from 'vuex'
  import NoResult from "../../base/no-result/no-result";

  let _this = null;
  const TYPE_SINGER = 'singer'
  const perpage = 20
  export default {
    props: {
      query:{
        type:String,
        default:''
      },
      //搜索出来的结果第一条是歌手
      showSinger:{
        type: Boolean,
        default: true
      }
    },
    data(){
      return {
        page:1,
        ret:[],
        pullup:true,
        //search刷新完的一个标志
        hasMore:true,
        beforeScroll:true
      }
    },
    mounted () {
      _this = this;
      _this.init();
      console.log(this.search.data.song.list)
    },
    methods: {
      init () {
      },
      refresh(){
        this.$refs.suggest.refresh()
      },
      _search(){
        //每次加载都是从1开始
        this.page = 1
        this.hasMore=true
        this.$refs.suggest.scrollTo(0,0)
        // search(this.query,this.page,this.showSinger,perpage).then((res) => {
        //   if(res.code === ERR_OK){
        //     // console.log(res.data)
        //     this.ret = this._genResult(res.data)
        //     //是否有多余的信息===第n页的信息
        //     this._checkMore(res.data)
        //   }
        // })
        if(this.query ===  this.search.data.keyword){
          this.ret = this._genResult(this.search.data)
          this._checkMore(this.search.data)
        }
      },
      //搜索时有没有更多信息===本质上还是search==========search相当于第一页的信息，searchMove是上拉时第n页的信息
      searchMove(){
        if(!this.hasMore){
          return
        }
        this.page++
        // search(this.query, this.page, this.showSinger, perpage).then((res) => {
        //   if (res.code === ERR_OK) {
        //     //this._genResult是赋值，这里是需要在数组添加数据
        //     this.ret = this.ret.concat(this._genResult(res.data))
        //     // console.log(this.ret)
        //     this._checkMore(res.data)
        //   }
        // })
        if(this.query ===  this.search.data.keyword){
          this.ret = this.ret.concat(this._genResult(this.search.data))
          this._checkMore(this.search.data)
        }


      },
      listScroll(){
        this.$emit('listScroll')
      },
      _genResult(data){
        // console.log(data)
        let ret =[]
        if(data.zhida && data.zhida.singerid){
          ret.push({...data.zhida,...{type:TYPE_SINGER}})
        }
        if(data.song){
          ret = ret.concat(this._normalizeSongs(data.song.list))
        }
        // console.log(ret)
        return ret
      },
      _normalizeSongs(list){
        let ret = []
        list.forEach((musicData) =>{
          if(isValidMusic(musicData)){
            ret.push(createSong(musicData))
          }
        })
        return ret
      },

      //判断信息是否全部展示
      _checkMore(data){
        const song = data.song
        //当所有信息全部的遍历完就将hasMore标志位为false
        if (!song.list.length || (song.curnum + song.curpage * perpage) >= song.totalnum) {
          this.hasMore = false
        }
      },
      selectItem(item){
        if(item.type === TYPE_SINGER){
          const singer = new Singer({
            id:item.singermid,
            name:item.singername
          })
          this.$router.push({
            path:`/search/${singer.id}`
          })
          this.setSinger(singer)
        }else{
          this.insertSong(item)
        }
        //给搜索历史铺垫
        this.$emit('select',item)
      },
      getIconCls(item){
        if(item.type === TYPE_SINGER){
          return 'icon-mine'
        }else{
          return 'icon-music'
        }
      },
      getDisplayName(item){
        // console.log(item)
        if(item.type === TYPE_SINGER){
          return item.singername
        }else{
          return `${item.name}-${item.singer}`
        }
      },
      ...mapMutations({
        setSinger: 'SET_SINGER'
      }),
      ...mapActions([
        'insertSong'
      ])
    },
    watch: {
      query(newQuery){
        this._search(newQuery)
      }
    },
    components: {NoResult, Loading, scroll},
    computed: {
      ...mapGetters([
        'search'
      ])
    },

  }
</script>


<style lang="stylus" rel="stylesheet/stylus">
  @import '../../common/stylus/variable.styl';
  @import "../../common/stylus/mixin.styl"
  .suggest
    height: 100%
    overflow: hidden
    .suggest-list
      padding: 0 30px
      .suggest-item
        display: flex
        align-items: center
        padding-bottom: 20px
      .icon
        flex: 0 0 30px
        width: 30px
        [class^="icon-"]
          font-size: 14px
          color: $color-text-d
      .name
        flex: 1
        font-size: $font-size-medium
        color: $color-text-d
        overflow: hidden
        .text
          no-wrap()
    .no-result-wrapper
      position: absolute
      width: 100%
      top: 50%
      transform: translateY(-50%)
</style>
